import 'package:flutter/material.dart';

// 缓存组件方法
class KeepAliveWrapper extends StatefulWidget {
  final bool keepAlive;
  final Widget child;

  const KeepAliveWrapper(
      {super.key, this.keepAlive = true, required this.child});

  @override
  State<StatefulWidget> createState() {
    return _KeepAliveWrapperState();
  }
}

// AutomaticKeepAliveClientMixin缓存组件（固定写法）
class _KeepAliveWrapperState extends State<KeepAliveWrapper>
    with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    // 被AutomaticKeepAliveClientMixin组件返回的widget组件就会被缓存
    // 这里重写父类的build方法
    super.build(context);
    return widget.child;
  }

  @override
  void didUpdateWidget(covariant KeepAliveWrapper oldWidget) {
    //状态发生变化时调用
    if (oldWidget.keepAlive != widget.keepAlive) {
      //更新KeepAlive状态
      updateKeepAlive();
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  bool get wantKeepAlive => true;
}
